package rctgl.util;

import java.io.ByteArrayInputStream;

public class RLEInputStream extends ByteArrayInputStream
{
	private static int COPY = 0;
	private static int DUPLICATE = 1;
	
	private int m_targetMode;
	private int m_targetLength;
	private int m_curLength;
	
	private int m_byteToCopy;
	
	
	public RLEInputStream(byte [] data)
	{
		super(data);
		
		m_curLength = 0;
		m_targetLength = 0;
	}


	@Override
	public synchronized int read()
	{
		int retVal = super.read();
		
		String byteStr = Integer.toBinaryString(retVal);
		
		if(retVal == -1)
			return retVal;
		
		//determine the next mode
		if(m_curLength == m_targetLength)
		{
			if((retVal & 0x80) == 0)
			{
				m_targetMode = COPY;
				m_targetLength = retVal + 1;
				m_curLength = 1;
				
				return super.read();
			}
			else
			{
				m_targetMode = DUPLICATE;
				m_byteToCopy = super.read();
				m_curLength = 1;
				
				m_targetLength = (retVal * -1) + 1;
				
				return m_byteToCopy;
				
			}
			
		}
		else
		{
			m_curLength++;
			
			if(m_targetMode == DUPLICATE)
			{
				return m_byteToCopy;
				
			}
			else
			{
				return retVal;
			}
		}
		
		
	}
	
	
	
	

}
